#!/bin/bash

# 数据库备份脚本
# 使用方法：在当前开发环境中运行此脚本

# 配置参数
DB_HOST="119.3.213.163"  # 当前数据库服务器
DB_PORT="3306"
DB_NAME="teacher_info_system"
DB_USER="root"
DB_PASSWORD="cjx12345@"

# 备份文件名（包含时间戳）
BACKUP_DATE=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="./database_backup"
BACKUP_FILE="${BACKUP_DIR}/teacher_info_system_backup_${BACKUP_DATE}.sql"

# 创建备份目录
mkdir -p ${BACKUP_DIR}

echo "开始备份数据库..."
echo "源数据库: ${DB_HOST}:${DB_PORT}/${DB_NAME}"
echo "备份文件: ${BACKUP_FILE}"

# 执行数据库备份
mysqldump -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWORD} \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    --set-gtid-purged=OFF \
    --default-character-set=utf8mb4 \
    --add-drop-table \
    --create-options \
    --disable-keys \
    --extended-insert \
    --quick \
    --lock-tables=false \
    ${DB_NAME} > ${BACKUP_FILE}

# 检查备份是否成功
if [ $? -eq 0 ]; then
    echo "数据库备份成功！"
    echo "备份文件大小: $(du -h ${BACKUP_FILE} | cut -f1)"
    
    # 压缩备份文件
    echo "正在压缩备份文件..."
    gzip ${BACKUP_FILE}
    echo "压缩完成: ${BACKUP_FILE}.gz"
    echo "压缩后大小: $(du -h ${BACKUP_FILE}.gz | cut -f1)"
    
    # 验证备份文件
    echo "验证备份文件完整性..."
    if zcat ${BACKUP_FILE}.gz | head -20 | grep -q "MySQL dump"; then
        echo "✅ 备份文件验证成功！"
    else
        echo "❌ 备份文件可能损坏，请检查！"
        exit 1
    fi
    
else
    echo "❌ 数据库备份失败！请检查连接参数和权限。"
    exit 1
fi

echo ""
echo "备份完成！请将以下文件传输到目标服务器："
echo "📁 ${BACKUP_FILE}.gz"
echo ""
echo "传输命令示例："
echo "scp ${BACKUP_FILE}.gz root@your-server:/opt/teacher-system/database_backup/"
